package com.xgc.book.bookserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xgc.book.bookserver.bean.BookBean;
import com.xgc.book.bookserver.bean.CategoryBean;
import com.xgc.book.bookserver.mapper.BookCategoryMapper;
import com.xgc.book.bookserver.mapper.CategoryMapper;
import com.xgc.book.bookserver.service.CategoryService;
import com.xgc.book.bookserver.util.ResultJson;
import com.xgc.book.bookserver.util.exception.RTException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 分类表 服务实现类
 * </p>
 *
 * @author wrz
 * @since 2023-11-20
 */
@Service
@Transactional
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, CategoryBean> implements CategoryService {

    @Autowired
    private BookCategoryMapper bookCategoryMapper;

    @Override
    public ResultJson getPage(int page, int limit, CategoryBean categoryBean) {
        IPage<CategoryBean> iPage = this.page(new Page<>(page, limit),
                new QueryWrapper<CategoryBean>()
                        .eq(StringUtils.isNotEmpty(categoryBean.getCategoryName()), "category_name",
                                categoryBean.getCategoryName())
                        .eq(categoryBean.getStatus() != null, "status", categoryBean.getStatus())
                        .orderByDesc("category_id"));
        return ResultJson.ok(iPage);
    }

    @Override
    public void delete(int categoryId) {
        IPage<BookBean> iPage = bookCategoryMapper.getBookByCategoryId(new Page<>(), categoryId);
        if (iPage.getTotal() > 0) {
            throw new RTException("该分类已被使用，无法删除！");
        } else {
            this.removeById(categoryId);
        }
    }
}
